package com.macro.mall.storage;

import cn.hutool.core.util.StrUtil;
import com.macro.mall.common.enums.SourceTypeEnum;
import com.macro.mall.dto.StorageObject;
import lombok.Getter;
import lombok.Setter;
import net.anumbrella.seaweedfs.core.FileTemplate;
import net.anumbrella.seaweedfs.core.file.FileHandleStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.entity.ContentType;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.stream.Stream;

/**
 * @author 郎
 */
public class SeaWeedStorage implements Storage {

    private final Log logger = LogFactory.getLog(SeaWeedStorage.class);

    @Getter
    @Setter
    private String host;
    @Getter
    @Setter
    private Integer port;
    @Getter
    @Setter
    private FileTemplate fileTemplate;

    @Getter
    @Setter
    private String publicDomain;

    /**
     * 七牛云OSS对象存储简单上传实现
     */
    @Override
    public StorageObject store(InputStream inputStream, long contentLength, String contentType, String keyName) {
        try {
            FileHandleStatus fileHandleStatus = fileTemplate.saveFileByStream(keyName, inputStream, ContentType.parse(contentType));
            logger.info("海藻对象存储的存储结果：" + fileHandleStatus.toString());
            String fullPath = fileHandleStatus.getFileUrl();
            if (StrUtil.isNotBlank(publicDomain)) {
                fullPath = publicDomain + fileHandleStatus.getFileId();
            }
            return new StorageObject(fullPath, keyName, fileHandleStatus.getFileId(), contentType, contentLength, SourceTypeEnum.SEAWEEDFS.getCode());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Stream<Path> loadAll() {
        return null;
    }

    @Override
    public Path load(String keyName) {
        return null;
    }

    @Override
    public Resource loadAsResource(String keyName) {
        try {
            URL url = new URL(generateUrl(keyName));
            Resource resource = new UrlResource(url);
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                return null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void delete(String fid) {
        try {
            fileTemplate.deleteFile(fid);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("SeaweedFS删除[" + fid + "]文件失败：" + e.getMessage());
        }
    }

    @Override
    public String generateUrl(String fid) {
        return "http://" + host + ":" + port + "/" + fid;
    }
}
